package com.homestay.controller;

import com.homestay.beans.Home;
import com.homestay.beans.Vip;
import com.homestay.exception.UsedException;
import com.homestay.service.HomeService;
import com.homestay.service.impl.HomeServiceImpl;
import com.homestay.utils.FormBeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@WebServlet("/HomeServlet.do")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10, // 10MB
        maxRequestSize = 1024 * 1024 * 50 // 50MB
)
public class HomeServlet extends HttpServlet {

    HomeService homeService = new HomeServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        switch (action) {
            case "add":
                addHome(request, response);
                break;
            case "delete":
                deleteHome(request, response);
                break;
            case "go_update":
                goUpdate(request, response);
                break;
            case "update":
                updateHome(request, response);
                break;
            case "list":
                getAllHomes(request, response);
                break;
            case "show":
                showHome(request, response);
                break;
            case "update_state":
                updateState(request, response);
                break;
            default:
                request.getRequestDispatcher("/views/error.jsp").forward(request, response);
        }
    }

    private void updateState(HttpServletRequest request, HttpServletResponse response) {

    }

    private void showHome(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");
            Home home = homeService.getHomeById(Integer.parseInt(id));
            if (home == null) {
                request.setAttribute("error", "房间信息不存在");
                request.getRequestDispatcher("/views/error.jsp").forward(request, response);
                return;
            }

            request.setAttribute("home", home);
            request.getRequestDispatcher("/views/home_show.jsp").forward(request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新房间信息的跳转方法
     *
     * @param request
     * @param response
     */
    private void goUpdate(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");
            Home home = homeService.getHomeById(Integer.parseInt(id));
            if (home == null) {
                request.setAttribute("error", "房间信息不存在");
                request.getRequestDispatcher("/views/error.jsp").forward(request, response);
                return;
            }
//            System.out.println("Updating home: " + home);
            request.setAttribute("home", home);
            request.getRequestDispatcher("/views/home_update.jsp").forward(request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取房间信息
     *
     * @param request
     * @param response
     */
    private void getAllHomes(HttpServletRequest request, HttpServletResponse response) {
        try {
            String num = request.getParameter("search_num");
//            System.out.println("Searching for homes with number: " + num);
            List<Home> homeList = homeService.getAllHomes(num);
            request.setAttribute("homeList", homeList);
            request.setAttribute("search_num", num);
            request.getRequestDispatcher("/views/home_list.jsp").forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
            request.setAttribute("error", "Error retrieving home list.");
            try {
                request.getRequestDispatcher("error.jsp").forward(request, response);
            } catch (ServletException | IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    private void updateHome(HttpServletRequest request, HttpServletResponse response) {
        try {
            Home home = FormBeanUtils.populate(request, Home.class);
            String img = home.getImg();
            String lastImg = request.getParameter("lastImg");
            System.out.println(img.equals(lastImg));
            if (!img.equals(lastImg)) {
                img = UUID.randomUUID().toString() + "." + img;
                // 保存上传的文件
                deleteFile(lastImg);
                saveFile(request, img);
                home.setImg("/upload/" + img);
            }

            int count = homeService.updateHome(home);
            if (count > 0) {
                response.getWriter().write("<script>alert('更新房间信息成功！');</script>");
                request.getRequestDispatcher("/HomeServlet.do?action=list").forward(request, response);
            } else {
                request.setAttribute("error", "更新房间信息失败，请检查输入信息");
                request.setAttribute("home", home);
                request.getRequestDispatcher("/views/home_update.jsp").forward(request, response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private void deleteHome(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            String id = request.getParameter("id");
            Home home = homeService.getHomeById(Integer.parseInt(id));
            String img = home.getImg();
            int count = homeService.deleteHome(Integer.parseInt(id));
            if (count > 0) {
                deleteFile(img);
                response.getWriter().write("<script>alert('删除房间成功！');location.href='/HomeServlet.do?action=list';</script>");
//                request.getRequestDispatcher("/HomeServlet.do?action=list").forward(request, response);
            } else {
                response.getWriter().write("<script>alert('删除房间失败！');location.href='/HomeServlet.do?action=list';</script>");
//                request.getRequestDispatcher("/HomeServlet.do?action=list").forward(request, response);
            }
        } catch (UsedException e) {
            String message = e.getMessage();
            System.out.println(message);
            response.getWriter().write("<script>alert('"+message+"');location.href='/HomeServlet.do?action=list';</script>");
//            request.getRequestDispatcher("/HomeServlet.do?action=list").forward(request, response);
        }

    }

    private void addHome(HttpServletRequest request, HttpServletResponse response) {
        try {
            Home home = FormBeanUtils.populate(request, Home.class);
            String img = home.getImg();
            String num = String.valueOf(home.getNum());
            img = UUID.randomUUID().toString() + "." + img;
            // 保存上传的文件
            saveFile(request, img);

            home.setImg("/upload/" + img);
            List<Home> homeList = homeService.getAllHomes(num);
            if (homeList != null && !homeList.isEmpty()) {
                request.setAttribute("error", "房间号已存在，请重新输入！");
                request.setAttribute("home", home);
                request.getRequestDispatcher("/views/home_add.jsp").forward(request, response);
                return;
            }
            int result = homeService.addHome(home);
            if (result > 0) {
                response.getWriter().write("<script>alert('添加房间成功！');</script>");
                request.setAttribute("num", "");
                request.getRequestDispatcher("/HomeServlet.do?action=list").forward(request, response);
            } else {
                request.setAttribute("error", "添加房间失败");
                request.setAttribute("home", home);
                request.getRequestDispatcher("/views/home_add.jsp").forward(request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }

    private void saveFile(HttpServletRequest request, String img) {
        try {
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                String fileName = part.getSubmittedFileName();
                if (fileName == null || fileName.isEmpty()) {
                    continue; // 跳过没有文件名的部分
                }
                part.write(getServletContext().getRealPath("/upload/") + img);
//                System.out.println(img);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }

    private void deleteFile(String img) {
        try {
            Files.delete(Paths.get(getServletContext().getRealPath("/upload/") + img.split("/")[2]));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
